package gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class MyFilter2 implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("this is a pre filter2");
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {

            System.out.println(exchange.getResponse().getStatusCode());
            exchange.getResponse().setStatusCode(HttpStatus.OK);
            byte[] bytes = "{\"code\":10,\"msg\":\"\",\"data\":null}".getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
            exchange.getResponse().writeWith(Flux.just(buffer));

            log.info("this is a post filter2");
        }));
    }

    @Override
    public int getOrder() {
        return -2;
    }
}

